package com.youmingxing.activity.login;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.WebViewActivity;
import com.youmingxing.bean.Web;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.ActivityJump;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.StringUtil;
import com.youmingxing.utils.Tools;
import com.youmingxing.view.TextCountWatcher;

import org.apache.http.Header;
import org.json.JSONObject;

/**
 * Created by JHS on 2015/9/9.
 */
public class LoginByMobleActivity extends BaseActivity implements View.OnClickListener {

    private TextView jumpRegister;
    private TextView agreementTv;
    private TextView forgetPwdTv;
    private Button loginBtn;
    /**
     * 电话号码输入框
     */
    private EditText mobileNumber;
    /**
     * 密码输入框
     */
    private EditText password;

    boolean numberChecked = false;
    boolean pwdChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_loginby_moble);
        initView();
    }

    private void initView() {
        setTopbarName(R.string.login_bymoble);
        jumpRegister = (TextView) findViewById(R.id.register_newuser);
        agreementTv = (TextView) findViewById(R.id.login_agreement_tv);
        forgetPwdTv = (TextView) findViewById(R.id.forget_pwd);
        loginBtn = (Button) findViewById(R.id.login_btn);
        mobileNumber = (EditText) findViewById(R.id.login_moble_edt);
        password = (EditText) findViewById(R.id.login_pw_edt);
        String argumentStr = "我同意《全民造星使用协议》";
        SpannableStringBuilder style = new SpannableStringBuilder(argumentStr);
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#E63E3E")), 3, argumentStr.length
                (), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        agreementTv.setText(style);
        jumpRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityJump.getInsanceJump(getApplication(), RegisterByMobileActivity.class, null);
            }
        });
        loginBtn.setOnClickListener(this);
        agreementTv.setOnClickListener(this);
        forgetPwdTv.setOnClickListener(this);
        jumpRegister.setOnClickListener(this);
        notClick();

        mobileNumber.addTextChangedListener(new TextCountWatcher(11) {
            @Override
            public void onTextMatchCount() {
                numberChecked = true;
                if (pwdChecked) {
                    canClick();
                }
            }

            @Override
            public void onTextLessThanCount() {
                numberChecked = false;
                notClick();
            }
        });
        password.addTextChangedListener(new TextCountWatcher(6) {
            @Override
            public void onTextMatchCount() {
                pwdChecked = true;
                if (numberChecked) {
                    canClick();
                }
            }

            @Override
            public void onTextLessThanCount() {
                pwdChecked = false;
                notClick();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.forget_pwd:
                intent = new Intent(this, RegisterByMobileActivity.class);
                intent.putExtra(RegisterByMobileActivity.EXTRAS_TYPE, RegisterByMobileActivity
                        .TYPE_FORGET_PWD);
                startActivity(intent);
                break;
            case R.id.login_agreement_tv:
                intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("web_page", Web.licence);
                startActivity(intent);
                break;
            case R.id.register_newuser:
                ActivityJump.getInsanceJump(this, RegisterByMobileActivity.class, null, true);
                break;
            case R.id.login_btn:
                String mobleStr = mobileNumber.getText().toString();
                String pwStr = password.getText().toString();
                if (StringUtil.isEmpty(mobleStr)) {
                    showToast(R.string.not_moble_num);
                    return;
                }
                if (StringUtil.isEmpty(pwStr)) {
                    showToast(R.string.loginpw_empty);
                    return;
                }
                if (Tools.isMobileNum(mobleStr)) {

                } else {
                    showToast(R.string.not_moble_num);
                    return;
                }
                AccountApi.login(mobleStr, StringUtil.generateMD5(pwStr), new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                if (response.optInt("status") == 200) {
                                    GlobalDataManager.token = response.optJSONObject("data").optString("token");
                                    GlobalDataManager.hx_pwd = response.optJSONObject("data").optString("hx_pwd");
                                    GlobalDataManager.hx_id = response.optJSONObject("data").optString("hx_id");
                                    LogUtil.i("------login--response---", GlobalDataManager.hx_id +
                                            " " + GlobalDataManager.hx_pwd);

                                    EMClient.getInstance().login(GlobalDataManager.hx_id, GlobalDataManager.hx_pwd,
                                            new EMCallBack() {
                                                @Override
                                                public void onSuccess() {
                                                    LogUtil.i("---------EMClient---","onSuccess");
                                                    // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                                                    // ** manually load all local groups and
                                                    EMClient.getInstance().groupManager().loadAllGroups();
                                                    EMClient.getInstance().chatManager().loadAllConversations();

                                                    // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                                                    boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                                                            AllStarApp.currentUserNick.trim());
                                                    if (!updatenick) {
                                                        Log.e("LoginActivity", "update current user nick fail");
                                                    }

                                                    // 进入主页面
                                                    Intent intent = new Intent(LoginByMobleActivity.this,
                                                            com.youmingxing.activity.MainActivity.class);
                                                    startActivity(intent);

                                                    finish();
                                                }

                                                @Override
                                                public void onProgress(int progress, String status) {
                                                }

                                                @Override
                                                public void onError(final int code, final String message) {
                                                    runOnUiThread(new Runnable() {
                                                        public void run() {
                                                        }
                                                    });
                                                    LogUtil.i("---------EMClient---","onError " + message);
                                                }
                                            });

                                    sharePreferenceUtil.setHXID(GlobalDataManager.hx_id);
                                    sharePreferenceUtil.setHXPWD(GlobalDataManager.hx_pwd);
                                    GlobalDataManager.save();
                                    //设置推送别名
                                    MiPushClient.setAlias(getApplicationContext(), GlobalDataManager.token, null);
                                    SelfInfoApi.getSelfInfo(new BaseJsonHandler
                                            (LoginByMobleActivity.this) {
                                        @Override
                                        public void onSuccessWithData(JSONObject response) {
                                            GlobalDataManager.userId = response.optJSONObject
                                                    ("data").optInt("id");
                                            GlobalDataManager.userInfo = response.toString();
                                            GlobalDataManager.save();
                                        }
                                    });
                                    finish();
                                } else {
                                    showToast(response.optString("statusText"));
                                }
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                showToast("登录失败,错误码:" + statusCode);
                            }
                        }
                );
                break;

        }
    }

    private void canClick() {
        loginBtn.setBackgroundResource(R.drawable.btn_redbg);
        loginBtn.setClickable(true);
    }

    private void notClick() {
        loginBtn.setBackgroundResource(R.drawable.btn_unable);
        loginBtn.setClickable(false);
    }
}
